# -*- coding: utf-8 -*-
# File : sync_mongo.py
# Author: taoyahui
# Date : 2021/7/1
from utils import mongo_util,mysql_util,common_util
import sys
from utils.log_util import logger


def sync_mongo_patch():
    """
    同步mongodb的patch collection数据到mysql的表
    定时启动，执行完之后清空mongodb的patch数据
    :return:
    """
    logger.info("*" * 10 + "sync_mongo_patch-> 开始执行同步补丁(mongodb)至数据库" + "*" * 10)
    res_list = mongo_util.find_by_condition("patch_distribute", "inventory_patch")
    for res in res_list:
        cve_id = res['cve_id']
        if patch_info_exists(cve_id.strip()) == 0:
            logger.info(f"Find new cve: ID is {cve_id}, need to update patch")
            save_patch(res)
    logger.info("*" * 5 + "sync_mongo_patch-> 完成执行同步补丁(mongodb)至数据库" + "*" * 5)

# 判断cve漏洞是否已存在
def patch_info_exists(cve_id):
    logger = common_util.get_logger(sys._getframe().f_code.co_name)

    """
    判断cve漏洞是否已存在
    :param cve_id:
    :return:
    """

    exist_sql = f"select count(1) from patch where cve_id = '{cve_id}'"
    result = mysql_util.exec_sql_new(exist_sql)
    if result[0][0] > 0:
        # logger.info(f"cve {cve_id} is existed!")
        return 1

    return 0


# 存储新增的补丁信息
def save_patch(patch_info):
    """
    存储新增的补丁信息
    :param patch_info:
    :return:
    """
    patch_info['adaptation_os'] = 2
    del patch_info['_id']
    del patch_info['hostname']

    # print(patch_info)
    insert_sql = mysql_util.generate_insert_sql(patch_info, 'patch')
    mysql_util.exec_sql_params(insert_sql, tuple(patch_info.values()))


if __name__ == '__main__':
    sync_mongo_patch()